# -*- coding:utf-8 -*-
import MySQLdb, json
import os
os.sys.path.append('../../utils/constants/')
from constants import *

class articleDao(object):
    "article: let me tell u sth about storage-visiting"
    def __init__(self, dbHandler):
        self.__nessary_list = [ (type(''), "content"), \
                             (type(''), "title"), \
                             (type(10), "creat_time"), \
                             (type(''), "summary"), \
                             (type(''), "imgurl"), \
                             #(type(''), "tags"), \
                             (type(10), "itype"),]
        self.__db_article_table = 'article'
        self.__list_size = 20
        self.__article_output_list = ['article_id', 'itype', 'like_count', 'creat_time', \
                'comm_count', 'pv_count', 'today_pv_count', 'imgurl', 'summary', 'title', ]
        self.__article_output_detail = ['article_id', 'itype', 'like_count', 'creat_time', \
                'comm_count', 'pv_count', 'imgurl', 'summary', 'title', 'content', ]
        self.__db_conn     = dbHandler

    def __is_valid(self, article_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not article_item:
            ret['retcode'] = E_VALUE_NONE
            ret['message'] = 'article_item is None'
            return ret
        for key_item in self.__nessary_list:
            if not article_item.has_key(key_item[1]):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = 'field[%s] not exist' % (key_item[1], )
                return ret
            if type(article_item[key_item[1]]) != key_item[0]:
                ret['retcode'] = E_VALUE_TYPE_ERROR
                ret['message'] = 'field[%s] type error. wish[%s]' % (key_item[1], key_item[0],)
                return ret
            if None == article_item[key_item[1]]:
                ret['retcode'] = E_VALUE_IS_EMPTY
                ret['message'] = 'field[%s] empty value' % (key_item[1], )
                return ret
        return ret

    def remove(self, delete_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"

        key_list = ['article_id', 'status',]
        for key in key_list:
            if not delete_item.has_key(key):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = "delete_item field [%s] not exist" % (key, )
                return ret
        strSQL = 'UPDATE %s SET status = %u WHERE article_id = %u;' % \
                (self.__db_article_table, delete_item['status'], delete_item['article_id'], )
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret
    def add(self, article_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        check_ret = self.__is_valid(article_item)
        if 0 != check_ret['retcode']:
            return check_ret
        article4insert = {}
        for key in self.__nessary_list:
            article4insert[key[1]] = article_item[key[1]]
        # 把tags变成一个字符串
        #if article_item.has_key('tags') and type(article_item['tags']) == type([]):
        #    article4insert['tags'] = '_'.join(article_item['tags'])
        #else:
        #    article4insert['tags'] = ''

        field_list = self.__nessary_list
        field_key_list = ''
        field_value_list = ''
        conn = self.__db_conn._db
        for  field in field_list:
            field_key_list += '%s, ' % (field[1],)
            if field[0] == type(10):
                field_value_list += '%u, ' % (article4insert[field[1]],)
            elif field[0] == type(''):
                field_value_list += '"%s", ' % (conn.escape_string(article4insert[field[1]].replace('%', '％')),)
            else:
                assert 0
        field_key_list = field_key_list[:-2] + ' '
        field_value_list = field_value_list[:-2] + ' '

        strSQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self.__db_article_table, field_key_list, field_value_list,)
        # -1- 插入article表
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def mod(self, article_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not article_item.has_key('article_id') :
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "article_item field [%s] not exist" % ('article_id', )
            return ret
        article_id = article_item['article_id']
        # 把tags变成一个字符串
        #if article_item.has_key('tags') and type(article_item['tags']) == type([]):
        #    article_item['tags'] = '_'.join(article_item['tags'])
        #else:
        #    article_item['tags'] = ''

        conn = self.__db_conn._db
        field_list = self.__nessary_list
        key_value_list = ''
        for  field in field_list:
            if not article_item.has_key(field[1]):
                continue
            key_value_list += '%s=' % (field[1],)
            if field[0] == type(10):
                key_value_list += '%u, ' % (article_item[field[1]],)
            elif field[0] == type(''):
                key_value_list += '"%s", ' % (conn.escape_string(article_item[field[1]].replace('%', '％')),)
            else:
                assert 0
        key_value_list = key_value_list[:-2] + ' '

        
        strSQL = 'UPDATE %s SET %s WHERE article_id = %u;' % (self.__db_article_table, key_value_list, article_id,)
        # -1- 插入article表
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def like(self, like_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # 检查合法性
        if not like_item.has_key('article_id') or not like_item.has_key('like'):
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "like_item field [%s] or [%s] not exist" % ('article_id', 'like', )
            return ret
        # -1- 更新article的like计数，锁表控制并发??
        #self.__db_conn.autocommit(False)
        strSQL  = 'SET AUTOCOMMIT = 0;'
        strSQL += ' SELECT like_count FROM article WHERE article_id=%u FOR UPDATE;' % (like_item['article_id'],)
        strSQL += ' UPDATE article SET like_count = like_count+1 WHERE article_id=%u;' % (like_item['article_id'],)
        strSQL += ' COMMIT; SET AUTOCOMMIT = 1;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        #self.__db_conn.commit()
        #self.__db_conn.autocommit(True)
        return ret

    def clear_today_pv(self):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        strSQL = 'UPDATE article SET today_pv_count = 0;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def add_pv_count(self, article_id):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # -1- 更新article的pv计数，锁表控制并发??
        #self.__db_conn.autocommit(False)
        strSQL  = 'SET AUTOCOMMIT = 0;'
        strSQL += ' SELECT pv_count, today_pv_count FROM article WHERE article_id=%u FOR UPDATE;' % (article_id,)
        strSQL += ' UPDATE article SET pv_count = pv_count+1, today_pv_count = today_pv_count+1 WHERE article_id=%u;' %\
                (article_id,)
        strSQL += ' COMMIT; SET AUTOCOMMIT = 1;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        #self.__db_conn.commit()
        #self.__db_conn.autocommit(True)
        return ret

    def get_detail(self, article_id,):

        select_list = self.__article_output_detail
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM %s WHERE article_id = %u and status = 0;' %\
                (select_key_string, self.__db_article_table, article_id,)
        detail_item = self.__db_conn.get(strSQL) 
        if not detail_item:
            return {}
        else:
            # 计算留到客户端去吧
            # if detail_item.has_key('tags'):
            #    detail_item['tags'] = detail_item['tags'].split('_')
            detail_item['imgurl'] = 'http://img.hb.aicdn.com/%s' % (detail_item['imgurl'])
            return detail_item

    def order_by(self, field, itype, pageno, desc = True):
        select_list = self.__article_output_list
        select_key_string = ', '.join(select_list)
        sort_order = desc and "DESC" or "ASC"
        if itype == 0:
            strSQL = 'SELECT %s FROM %s WHERE status = 0 ORDER BY %s %s limit %u, %u;' %\
                    (select_key_string, self.__db_article_table, field, \
                    sort_order, pageno*self.__list_size, self.__list_size)
        else:
            strSQL = 'SELECT %s FROM %s WHERE status = 0 and itype = %u ORDER BY %s %s limit %u, %u;' %\
                    (select_key_string, self.__db_article_table, itype, field, \
                    sort_order, pageno*self.__list_size, self.__list_size)
        retlist = self.__db_conn.query(strSQL)
        # 当且仅当pageno=0第一页时，前三个结果为大图用作幻灯片，否则全部替换成小图，提高加载速度
        for x in range(len(retlist)):
            if pageno > 0 or (pageno == 0 and x > 2):
                retlist[x]['imgurl'] = 'http://img.hb.aicdn.com/%s_fw192' % (retlist[x]['imgurl'])
            else:
                retlist[x]['imgurl'] = 'http://img.hb.aicdn.com/%s_fw554' % (retlist[x]['imgurl'])
        return retlist
